<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="3" :xs="24">
        <div class="head-container">
          <el-input
            v-model="nameStatus"
            placeholder="请输入"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="shipmentStatusOptions"
            :props="defaultShipmentStatus"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="SKU" prop="searchSku">
            <el-input
              v-model="queryParams.searchSku"
              placeholder="请输入计划名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="计划名称" prop="planName">
            <el-input
              v-model="queryParams.planName"
              placeholder="请输入计划名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item
            label="销售计划编号"
            prop="planNumber"
            label-width="100px"
          >
            <el-input
              v-model="queryParams.planNumber"
              placeholder="请输入销售计划编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- <el-form-item
            label="采购计划编号"
            prop="procuredPlanNumber"
            label-width="100px"
          >
            <el-input
              v-model="queryParams.procuredPlanNumber"
              placeholder="请输入采购计划编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item> -->
          <el-form-item
            label="采购单号"
            prop="procuredOrdersNumber"
            label-width="100px"
          >
            <el-input
              v-model="queryParams.procuredOrdersNumber"
              placeholder="请输入采购计划编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['sale:plan:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['sale:plan:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['sale:plan:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['sale:plan:export']"
              >导出</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-folder-checked"
              size="mini"
              @click="underReview"
              >审核</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              size="mini"
              icon="el-icon-s-opportunity"
              :disabled="single"
              @click="handleAudit"
              v-hasPermi="['sale:plan:revoke']"
              >撤回</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="planList"
          @selection-change="handleSelectionChange"
          ref="table"
          @expand-change="handleExpandChange"
          height="calc(100vh - 200px)"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column align="center" width="20" type="expand">
            <template slot-scope="scope">
              <el-table
                :data="scope.row.shipmentsProductList"
                :span-method="nestedTableSpanMethod"
                ref="nestedTable"
              >
                <el-table-column
                  label="图片"
                  align="center"
                  prop="imgName"
                  min-width="90"
                >
                  <template slot-scope="scope">
                    <div class="image-container">
                      <template
                        v-if="scope.row.imgName && scope.row.imgName.length > 0"
                      >
                        <image-preview
                          v-for="(image, index) in scope.row.imgName"
                          :key="index"
                          :src="image"
                          :width="50"
                          :height="50"
                          class="image-item"
                        />
                      </template>
                      <span v-else>-</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="品名" prop="name" align="center">
                  <template slot-scope="scope">
                    <el-tooltip
                      v-if="scope.row.name"
                      :content="scope.row.name"
                      placement="top"
                      effect="light"
                    >
                      <div class="ellipsis-cell">{{ scope.row.name }}</div>
                    </el-tooltip>
                    <span v-else>-</span>
                  </template>
                </el-table-column>

                <el-table-column label="SKU" align="center" prop="sku">
                  <template slot-scope="scope">
                    <el-tooltip
                      v-if="scope.row.sku"
                      :content="scope.row.sku"
                      placement="top"
                      effect="light"
                    >
                      <div class="ellipsis-cell">{{ scope.row.sku }}</div>
                    </el-tooltip>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column label="GTIN" prop="gtin" align="center">
                </el-table-column>
                <el-table-column
                  label="SellerSKU"
                  prop="itemSku"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  label="已发数量"
                  prop="sentSize"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  label="未发数量"
                  prop="operSize"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  label="计划数量"
                  align="center"
                  prop="planSize"
                  min-width="100"
                >
                  <template slot-scope="scope">
                    <span>
                      {{ scope.row.planSize }}个
                      <span v-if="scope.row.terminatedQuantity">
                        (原：{{
                          scope.row.terminatedQuantity + scope.row.planSize
                        }}个)
                      </span>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="合计数量" align="center">
                  <template slot-scope="scope">
                    <span v-if="scope.row._rowIndex === scope.row._skuFirstRow">
                      {{ scope.row._skuTotal }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="产品备注" prop="remark" align="center">
                </el-table-column>
                <el-table-column
                  label="操作"
                  fixed="right"
                  align="center"
                  class-name="small-padding fixed-width"
                  width="100px"
                >
                  <template slot-scope="innerScope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-close"
                      v-show="
                        scope.row.planStatus == 1 &&
                        Number(innerScope.row.operSize) > 0 &&
                        Number(innerScope.row.planSize) > 0
                      "
                      @click="
                        handleEndPlan(
                          scope.row.id,
                          innerScope.row.id,
                          scope.row.planNumber
                        )
                      "
                      v-hasPermi="['sale:plan:end']"
                      >提前结束</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column
            label="计划编号"
            align="center"
            prop="planNumber"
            width="150px"
          >
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="light"
                :content="scope.row.planNumber"
                placement="top"
              >
                <span>{{ scope.row.planNumber }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="计划名称" align="center" prop="planName">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="light"
                :content="scope.row.planName"
                placement="top"
              >
                <span>
                  {{ (scope.row.planName || "").slice(0, 10) }}
                  <span v-if="(scope.row.planName || '').length > 10">...</span>
                </span>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column
            label="发货日期"
            align="center"
            prop="shipTime"
            width="100px"
          >
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="light"
                :content="parseTime(scope.row.shipTime, '{y}-{m}-{d}')"
                placement="top"
              >
                <span>{{ parseTime(scope.row.shipTime, "{y}-{m}-{d}") }}</span>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column
            label="货运方式"
            align="center"
            prop="mannerName"
            width="180px"
          >
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="light"
                :content="scope.row.mannerName"
                placement="top"
              >
                <span>
                  {{ (scope.row.mannerName || "").slice(0, 10) }}
                  <span v-if="(scope.row.mannerName || '').length > 10"
                    >...</span
                  >
                </span>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column label="发往店铺" align="center" prop="shopName">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="light"
                :content="scope.row.shopName"
                placement="top"
              >
                <span>{{ scope.row.shopName }}</span>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column label="制单人" align="center" prop="nickName">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="light"
                :content="scope.row.nickName"
                placement="top"
              >
                <span>{{ scope.row.nickName }}</span>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column label="审核状态" align="center" prop="planStatus">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="light"
                :content="scope.row.planStatus"
                placement="top"
              >
                <dict-tag
                  :options="dict.type.tb_plan"
                  :value="scope.row.planStatus"
                />
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column
            label="发货状态"
            align="center"
            prop="shippingStatus"
          >
            <template slot-scope="scope">
              <el-tooltip class="item" effect="light" placement="top">
                <dict-tag
                  :options="dict.type.sys_sales_shipment_status"
                  :value="scope.row.shippingStatus"
                />
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column
            label="制单日期"
            align="center"
            prop="preparationTime"
            width="135"
          >
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="light"
                :content="
                  parseTime(scope.row.preparationTime, '{y}-{m}-{d}') +
                  ' ' +
                  parseTime(scope.row.preparationTime, '{h}:{i}')
                "
                placement="top"
              >
                <span
                  >{{ parseTime(scope.row.preparationTime, "{y}-{m}-{d}") }}
                  {{ parseTime(scope.row.preparationTime, "{h}:{i}") }}</span
                >
              </el-tooltip>
            </template>
          </el-table-column>

          <!-- <el-table-column label="审核人" align="center" prop="approver" />
          <el-table-column label="审核日期" align="center" prop="auditTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.auditTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column> -->

          <el-table-column label="采购计划号" align="center" width="150px">
            <template slot-scope="{ row }">
              <div v-if="row.procuredPlanNumber">
                <el-tooltip placement="top" :open-delay="300">
                  <div
                    slot="content"
                    style="user-select: text; white-space: pre-line"
                  >
                    {{ row.procuredPlanNumber.split(",").join("\n") }}
                  </div>
                  <div class="plan-number-display">
                    {{ row.procuredPlanNumber.split(",")[0] }}
                    <span
                      v-if="row.procuredPlanNumber.includes(',')"
                      class="more-indicator"
                    >
                      +{{ row.procuredPlanNumber.split(",").length - 1 }}
                    </span>
                  </div>
                </el-tooltip>
              </div>
              <div v-else style="color: #999">—</div>
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            align="center"
            prop="remark"
            width="170px"
          >
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="light"
                :content="scope.row.remark"
                placement="top"
              >
                <span>
                  {{ (scope.row.remark || "").slice(0, 10) }}
                  <span v-if="(scope.row.remark || '').length > 10">...</span>
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            class-name="small-padding fixed-width"
            width="100px"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.planStatus != 1"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['sale:plan:edit']"
                >修改</el-button
              >
              <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handlePlanQuery(scope.row)"
                v-hasPermi="['sale:plan:query']">详情</el-button> -->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                v-if="scope.row.planStatus != 1"
                @click="handleDelete(scope.row)"
                v-hasPermi="['sale:plan:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改销售中心对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="90%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="计划编号" prop="planNumber">
              <el-input
                :disabled="true"
                v-model="form.planNumber"
                placeholder="系统自动填计划编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发往店铺" prop="goShop">
              <el-cascader
                v-model="form.platForm"
                :options="platFormOptions"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="期望发货" prop="shipTime">
              <el-date-picker
                clearable
                v-model="form.shipTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择发货时间"
                :default-value="new Date().toISOString().split('T')[0]"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货运方式" prop="freightMethod">
              <treeselect
                v-model="form.freightMethod"
                :options="freightMethodOptions"
                :show-count="true"
                placeholder="请输入货运方式"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddShipmentsProduct"
              v-if="decide"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteShipmentsProduct"
              v-if="decide"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="shipmentsProductList"
          :row-class-name="rowShipmentsProductIndex"
          @selection-change="handleShipmentsProductSelectionChange"
          ref="shipmentsProduct"
          height="330px"
          :span-method="tableSpanMethod"
        >
          <!-- 选择列 -->
          <el-table-column type="selection" width="50" align="center" />

          <!-- 图片列 -->
          <el-table-column
            label="图片"
            align="center"
            prop="imgName"
            min-width="90"
          >
            <template slot-scope="scope">
              <div class="image-container">
                <template
                  v-if="scope.row.imgName && scope.row.imgName.length > 0"
                >
                  <image-preview
                    v-for="(image, index) in scope.row.imgName"
                    :key="index"
                    :src="image"
                    :width="50"
                    :height="50"
                    class="image-item"
                  />
                </template>
                <span v-else>-</span>
              </div>
            </template>
          </el-table-column>

          <!-- 名称列 -->
          <el-table-column
            label="名称"
            prop="name"
            align="center"
            min-width="150"
          >
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.name"
                :content="scope.row.name"
                placement="top"
                :disabled="scope.row.name.length <= 10"
              >
                <span class="text-ellipsis">
                  {{ scope.row.name.slice(0, 10) }}
                  <span v-if="scope.row.name.length > 10">...</span>
                </span>
              </el-tooltip>
              <span v-else>-</span>
            </template>
          </el-table-column>

          <!-- sku 列 -->
          <el-table-column
            label="SKU"
            prop="sku"
            align="center"
            min-width="150"
          >
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.sku"
                :content="scope.row.sku"
                placement="top"
                :disabled="scope.row.sku.length <= 10"
              >
                <span class="text-ellipsis">
                  {{ scope.row.sku.slice(0, 10) }}
                  <span v-if="scope.row.sku.length > 10">...</span>
                </span>
              </el-tooltip>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <!-- GTIN 列：保持原样，不参与合并 -->
          <el-table-column
            label="GTIN"
            prop="gtin"
            align="center"
            min-width="180"
          >
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.gtin"
                :content="scope.row.gtin"
                placement="top"
                :disabled="scope.row.gtin.length <= 14"
              >
                <span class="text-ellipsis">
                  {{ scope.row.gtin.slice(0, 14) }}
                  <span v-if="scope.row.gtin.length > 14">...</span>
                </span>
              </el-tooltip>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <!-- SellerSKU -->
          <el-table-column
            label="SellerSKU"
            prop="sellerSku"
            align="center"
            min-width="180"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.sellerSku || "-" }}</span>
            </template>
          </el-table-column>

          <!-- 已发数量列 -->
          <el-table-column
            label="已发数量"
            prop="sentSize"
            min-width="100"
            align="center"
          />

          <!-- 未发数量列 -->
          <el-table-column
            label="未发数量"
            prop="operSize"
            min-width="100"
            align="center"
          />

          <!-- 计划数量列 -->
          <el-table-column
            label="计划数量"
            prop="planSize"
            min-width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.planSize"
                placeholder="请输入计划数量"
                @input="autoFillModel(scope.row)"
              />
            </template>
          </el-table-column>

          <!-- 总计数量列（新增） -->
          <el-table-column
            label="总计数量"
            prop="totalPlan"
            min-width="100"
            align="center"
          >
            <template slot-scope="scope">
              <!-- 只有组的第一行显示合计，其它被合并的单元格不显示 -->
              <span>{{ skuPlanTotals[scope.row.sku] }}</span>
            </template>
          </el-table-column>

          <!-- 产品备注列 -->
          <el-table-column
            label="产品备注"
            min-width="180"
            prop="productRemarks"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.productRemarks"
                placeholder="请输入产品备注"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="decide"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加产品 -->
    <el-dialog
      :title="titleName"
      :visible.sync="productOpen"
      width="80%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-row :gutter="20">
        <!-- 产品分类 -->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input
              v-model="productsName"
              placeholder="请输入产品名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="productsOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClickProduct"
            />
          </div>
        </el-col>
        <!-- 产品信息 -->
        <el-col :span="20" :xs="24">
          <el-form
            :model="queryParamProduct"
            ref="queryFormProduct"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="商品名称" prop="name">
              <el-input
                v-model="queryParamProduct.name"
                placeholder="请输入商品名称"
                clearable
                @keyup.enter.native="handleQueryProduct"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParamProduct.status"
                placeholder="请选择状态"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.sys_job_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQueryProduct"
                >搜索</el-button
              >
              <el-button
                icon="el-icon-refresh"
                size="mini"
                @click="resetQueryProduct"
                >重置</el-button
              >
            </el-form-item>
          </el-form>

          <!-- 添加外部滚动容器 -->
          <div
            style="
              max-width: 100%;
              overflow-x: auto;
              -webkit-overflow-scrolling: touch;
            "
          >
            <el-table
              v-loading="loadingProduct"
              :data="productsList"
              @selection-change="handleSelectionChange"
              height="510px"
              ref="myTable"
              style="width: 100%"
            >
              <!-- GTIN列 -->
              <el-table-column
                label="GTIN"
                align="center"
                prop="gtin"
                min-width="150px"
                fixed="right"
              >
                <template slot-scope="scope">
                  <span :title="scope.row.gtin">{{
                    scope.row.gtin || "-"
                  }}</span>
                </template>
              </el-table-column>
              <!-- Walmart产品链接列，固定到右侧 -->
              <el-table-column
                label="walmart产品链接"
                align="center"
                prop="walmartProductName"
                min-width="150px"
                fixed="right"
              >
                <template slot-scope="scope">
                  <el-tooltip
                    v-if="scope.row.walmartProductName"
                    class="item"
                    effect="dark"
                    :content="scope.row.walmartProductName"
                    placement="top-start"
                  >
                    <span
                      style="
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        user-select: text;
                      "
                    >
                      {{ scope.row.walmartProductName }}
                    </span>
                  </el-tooltip>
                  <span v-else>-</span>
                </template>
              </el-table-column>

              <!-- Walmart产品图片列，固定到右侧 -->
              <el-table-column
                label="walmart产品图片"
                align="center"
                prop="walmartImageUrl"
                min-width="150px"
                fixed="right"
              >
                <template slot-scope="scope">
                  <image-preview
                    :src="scope.row.walmartImageUrl"
                    :width="50"
                    :height="50"
                  />
                </template>
              </el-table-column>

              <el-table-column type="selection" min-width="50" align="center" />

              <!-- 图片列 -->
              <el-table-column
                label="图片"
                align="center"
                prop="imgName"
                min-width="90"
              >
                <template slot-scope="scope">
                  <div class="image-container">
                    <image-preview
                      v-for="(image, index) in scope.row.imgName"
                      :key="index"
                      :src="image"
                      :width="50"
                      :height="50"
                      class="image-item"
                    />
                  </div>
                </template>
              </el-table-column>

              <!-- 名称列：强制一行显示，鼠标悬停显示完整内容 -->
              <el-table-column
                label="名称"
                align="center"
                prop="name"
                min-width="150px"
              >
                <template slot-scope="scope">
                  <el-tooltip
                    v-if="scope.row.name"
                    class="item"
                    effect="dark"
                    :content="scope.row.name"
                    placement="top-start"
                  >
                    <span
                      style="
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        user-select: text;
                      "
                    >
                      {{ scope.row.name }}
                    </span>
                  </el-tooltip>
                  <span v-else>-</span>
                </template>
              </el-table-column>

              <!-- 产品SKU列 -->
              <el-table-column
                label="产品SKU"
                align="center"
                prop="sku"
                min-width="150px"
              >
                <template slot-scope="scope">
                  <span :title="scope.row.sku">{{ scope.row.sku || "-" }}</span>
                </template>
              </el-table-column>

              <!-- 单价列 -->
              <el-table-column
                label="单价(￥)"
                align="center"
                prop="price"
                min-width="150px"
              >
                <template slot-scope="scope">
                  <span :title="scope.row.price">{{
                    scope.row.price || "-"
                  }}</span>
                </template>
              </el-table-column>

              <!-- 店铺列 -->
              <!-- <el-table-column label="店铺" align="center" prop="shopName" min-width="150px">
                <template slot-scope="scope">
                  <span :title="scope.row.shopName">{{ scope.row.shopName || '-' }}</span>
                </template>
              </el-table-column> -->

              <!-- 品牌名称列 -->
              <el-table-column
                label="品牌名称"
                align="center"
                prop="brandName"
                min-width="150px"
              >
                <template slot-scope="scope">
                  <span :title="scope.row.brandName">{{
                    scope.row.brandName || "-"
                  }}</span>
                </template>
              </el-table-column>

              <!-- 产品介绍列 -->
              <el-table-column
                label="产品介绍"
                align="center"
                prop="desc"
                min-width="150px"
              >
                <template slot-scope="scope">
                  <span
                    :title="scope.row.desc"
                    style="
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                    "
                  >
                    {{ scope.row.desc || "-" }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <pagination
            v-show="totalProduct > 0"
            :total="totalProduct"
            :page.sync="queryParamProduct.pageNum"
            :limit.sync="queryParamProduct.pageSize"
            @pagination="getListProduct"
          />
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormProduct">确 定</el-button>
        <el-button @click="cancelProduct">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核申请 -->
    <el-dialog
      :title="audit"
      :visible.sync="openAudit"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div>
        <el-tabs
          type="border-card"
          class="auditStyle"
          @tab-click="handleTabClick"
          v-model="activeTab"
        >
          <el-tab-pane name="toAudit">
            <span slot="label"><i class="el-icon-date"></i>待我审核</span>
            <div class="head-container">
              <el-input
                v-model="nickName"
                placeholder="请输入申请人"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
                @input="
                  () => {
                    pageParams.audited.pageNum = 1;
                    loadData();
                  }
                "
              />
            </div>
            <div class="show-frame-container">
              <template
                v-if="tabData[activeTab] && tabData[activeTab].length > 0"
              >
                <div
                  class="show-frame"
                  v-for="(item, index) in tabData[activeTab]"
                  :key="index"
                  @click="borderTrigger(item)"
                >
                  <image-preview :src="item.avatar" :width="50" :height="50" />

                  <div class="plan-size">
                    <h4>{{ item.nickName }}提交的销售计划</h4>
                  </div>
                  <div class="singleHanded-css">
                    申请人：{{ item.nickName }}
                  </div>

                  <div class="planNumber-css">
                    计划编号：{{ item.planNumber }}
                  </div>

                  <div class="mannerName-css">
                    货运方式：{{ item.mannerName }}
                  </div>
                  <div class="shipTimeMy-css" style="">
                    {{ parseTime(item.shipTime, "{y}-{m}-{d}") }}
                  </div>
                  <div class="planStatusMy-css">
                    <dict-tag
                      :options="dict.type.tb_plan"
                      :value="item.planStatus"
                    />
                    <el-button
                      type="text"
                      style="margin-left: 15px"
                      @click.stop="planProcessLog(item)"
                      >日志记录</el-button
                    >
                  </div>
                </div>
              </template>
              <div v-else class="no-data">暂无数据。</div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="我已审核" name="audited">
            <el-input
              v-model="nickNameReviewed"
              placeholder="请输入申请人"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
              @input="
                () => {
                  pageParams.audited.pageNum = 1;
                  loadData();
                }
              "
            />
            <div class="show-frame-container">
              <template v-if="tabData[activeTab].length > 0">
                <div
                  class="show-frame"
                  v-for="(item, index) in tabData[activeTab]"
                  :key="index"
                >
                  <image-preview :src="item.avatar" :width="50" :height="50" />

                  <div class="plan-size">
                    <h4>{{ item.nickName }}提交的销售计划</h4>
                  </div>
                  <div class="singleHanded-css">
                    申请人：{{ item.nickName }}
                  </div>

                  <div class="planNumber-css">
                    计划编号：{{ item.planNumber }}
                  </div>

                  <div class="mannerName-css">
                    货运方式：{{ item.mannerName }}
                  </div>

                  <div class="planProcessTime-css">
                    审核时间：{{
                      parseTime(item.planProcessTime, "{y}-{m}-{d}-{h}:{m}:{s}")
                    }}
                  </div>

                  <div class="planProcessStatus-css">
                    <dict-tag
                      :options="dict.type.tb_plan"
                      :value="item.planProcessStatus"
                    />
                    <el-button
                      type="text"
                      style="margin-left: 15px"
                      @click="planProcessLog(item)"
                      >日志记录</el-button
                    >
                  </div>

                  <div class="shipTimeReady-css">
                    {{ parseTime(item.shipTime, "{y}-{m}-{d}") }}
                  </div>

                  <div class="planStatus-css">
                    <dict-tag
                      :options="dict.type.tb_plan"
                      :value="item.planStatus"
                    />
                  </div>
                </div>
              </template>
              <div v-else class="no-data">暂无数据。</div>
            </div>
          </el-tab-pane>
          <el-tab-pane name="myAudit" label="我发起的">
            <div class="show-frame-container">
              <template v-if="tabData[activeTab].length > 0">
                <div
                  class="show-frame"
                  v-for="(item, index) in tabData[activeTab]"
                  :key="index"
                >
                  <image-preview :src="item.avatar" :width="50" :height="50" />

                  <div class="plan-size">
                    <h4>{{ item.nickName }}提交的销售计划</h4>
                  </div>
                  <div class="singleHanded-css">
                    申请人：{{ item.nickName }}
                  </div>

                  <div class="planNumber-css">
                    计划编号：{{ item.planNumber }}
                  </div>

                  <div class="mannerName-css">
                    货运方式：{{ item.mannerName }}
                  </div>
                  <div class="shipTimeMy-css" style="">
                    {{ parseTime(item.shipTime, "{y}-{m}-{d}") }}
                  </div>
                  <div class="planStatusMy-css">
                    <dict-tag
                      :options="dict.type.tb_plan"
                      :value="item.planStatus"
                    />
                    <el-button
                      type="text"
                      style="margin-left: 15px"
                      @click="planProcessLog(item)"
                      >日志记录</el-button
                    >
                  </div>
                </div>
              </template>
              <div v-else class="no-data">暂无数据。</div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <pagination
        v-show="tabTotals[activeTab] > 0"
        :total="tabTotals[activeTab]"
        :page.sync="pageParams[activeTab].pageNum"
        :limit.sync="pageParams[activeTab].pageSize"
        @pagination="handlePagination"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelTreat">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer title="详情" :visible.sync="drawer">
      <div class="drawerValueUserImg">
        <image-preview
          :src="this.drawerValue.avatar"
          :width="50"
          :height="50"
        />
      </div>
      <div class="drawerValueSingleHanded">
        <h3>{{ this.drawerValue.nickName }}提交的销售计划</h3>
      </div>
      <div class="drawerValuePlanStatus">
        <dict-tag
          :options="dict.type.tb_plan"
          :value="this.drawerValue.planStatus"
        />
      </div>
      <el-descriptions class="margin-top" :column="1" direction="vertical">
        <el-descriptions-item label="计划编号"
          ><span style="color: black">{{
            this.drawerValue.planNumber
          }}</span></el-descriptions-item
        >
        <el-descriptions-item label="申请人"
          ><span style="color: black">{{
            this.drawerValue.nickName
          }}</span></el-descriptions-item
        >
        <el-descriptions-item label="部门">
          <span style="color: black">{{
            this.drawerValue.deptName
          }}</span></el-descriptions-item
        >
        <el-descriptions-item label="货运方式">
          <span style="color: black">
            {{ this.drawerValue.mannerName }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="发货的商品" v-if="this.productLength > 0">
          <span v-for="i in this.productLength" :key="i" style="color: black">
            《{{ drawerValue.shipmentsProductList[i - 1].productName }}》
          </span>
        </el-descriptions-item>
      </el-descriptions>
      <hr />
      <div>
        <div>
          <image-preview
            :src="this.drawerValue.avatar"
            :width="50"
            :height="50"
          />
          <div class="sponsor">发起人</div>
          <div class="sponsor-name">{{ this.drawerValue.nickName }}</div>
          <div class="sponsor-time">
            {{ parseTime(this.drawerValue.preparationTime, "{y}-{m}-{d}") }}
            {{ parseTime(this.drawerValue.preparationTime, "{h}:{i}") }}
          </div>
        </div>
        <div class="_scroll-container">
          <div
            v-for="(item, index) in planProcessData"
            :key="index"
            :class="index === 0 ? '' : 'postUserDept-css'"
          >
            <image-preview :src="item.avatar" :width="50" :height="50" />
            <div class="sponsor">审批人</div>
            <div class="sponsor-name">
              {{ item.nickName }}
              <span
                v-if="item"
                v-show="
                  item.planProcessStatus == 4 || item.planProcessStatus == null
                "
              >
                (审核中)
              </span>
              <span v-if="item" v-show="item.planProcessStatus == 1">
                (同意)&nbsp;&nbsp;{{ item.planProcessTime }}
              </span>
              <span v-if="item" v-show="item.planProcessStatus == 0">
                (拒绝)
              </span>
            </div>
            <div class="sponsor-time">
              {{ item.deptName }}
            </div>
            <div class="postUserDept-postName">
              {{ item.roleName }}
            </div>
          </div>
        </div>
        <!-- <div>
          <div class="block">
            <el-avatar shape="square" :size="50" :src="squareUrl" style="
                height: 50px;
                width: 50px;
                line-height: 50px;
                background-color: #1890ff;
              " />
          </div>
          <div class="ccPerson">抄送人</div>
          <div class="sponsor-name">已{{ imageCount }}抄送人</div>
          <div class="sponsor-time">
            {{ parseTime(currentDateTime, "{y}-{m}-{d}") }}
            {{ parseTime(currentDateTime, "{h}:{i}") }}
          </div>
          <div class="approvalProcess-container">
            <div v-for="i in this.ApprovalProcessLength" :key="i" class="approvalProcess-image">
              <image-preview :src="ApprovalProcessStatus[i - 1].avatar" :width="30" :height="30"
                v-if="ApprovalProcessStatus[i - 1].status == 1" />
              <div class="approvalProcess-size" v-if="ApprovalProcessStatus[i - 1].status == 1">
                {{ ApprovalProcessStatus[i - 1].nickName }}
              </div>
            </div>
          </div>
        </div> -->
      </div>
      <div class="approval">
        <el-input
          v-model="planProcessRemark"
          type="textarea"
          class="processRemark-input"
          placeholder="备注填写"
          rows="3"
        ></el-input>
        <div class="button-group">
          <el-button @click="rejectPlan(drawerValue.id, 0)" type="danger"
            >拒 绝</el-button
          >
          <el-button type="primary" @click="approvePlan(drawerValue.id, 1)"
            >同 意</el-button
          >
        </div>
      </div>
    </el-drawer>

    <!-- 审核日志记录 -->
    <el-dialog
      :visible.sync="openLog"
      width="1400px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-table v-loading="loading" :data="PlanProcessLogList" height="500px">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="销售计划单号"
          align="center"
          prop="planNumber"
          width="135"
        />
        <el-table-column
          label="审核状态"
          align="center"
          prop="planLogStatus"
          width="135"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.tb_plan"
              :value="scope.row.planLogStatus"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="审核人"
          align="center"
          prop="planLogApplicant"
        />
        <el-table-column label="审核时间" align="center" prop="planLogTime">
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.planLogTime, "{y}-{m}-{d} {h}:{m}:{s}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核备注" align="center" prop="planLogRemark" />
        <el-table-column label="制单人" align="center" prop="nickName" />
        <el-table-column label="制单日期" align="center" prop="preparationTime">
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.preparationTime, "{y}-{m}-{d} {h}:{m}:{s}")
            }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="logTotals > 0"
        :total="logTotals"
        :page.sync="logParam.pageNum"
        :limit.sync="logParam.pageSize"
        @pagination="getPlanProcessLogList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPlanProcessLog">取消</el-button>
      </div>
    </el-dialog>

    <!-- 撤回审核 -->
    <el-dialog
      title="撤回"
      :visible.sync="openRevoke"
      v-model="dialogVisible"
      width="400px"
    >
      <el-form :model="revoke">
        <el-form-item label="撤回备注：" label-width="100px">
          <el-input
            type="textarea"
            v-model="revoke.remark"
            placeholder="请输入撤回备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeRevoke">取消</el-button>
        <el-button type="primary" @click="confirmWithdraw">确定</el-button>
      </template>
    </el-dialog>

    <!-- 提前结束的弹窗 -->
    <el-dialog
      title="提前结束销售计划"
      :visible.sync="showEndPlanDialog"
      width="400px"
      append-to-body
    >
      <el-form :model="form" label-width="140px">
        <el-form-item label="结束后的发货数量" prop="endShippingQuantity">
          <el-input
            v-model="endShippingQuantity"
            type="number"
            label="发货数量"
            placeholder="请输入结束后的发货数量"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeEndPlanDialog">取消</el-button>
        <el-button type="primary" @click="submitEndPlan">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  endPlan,
  getShipmentStatus,
  getFreightMethodTree,
  getSelectItemPlan,
  getSelectPairId,
  getUpdatePlanStatusById,
  SearchRelatedPurchaseOrders,
  getPlanWaitProcessList, //待我审核
  getPlanProcessList, //审核流程数据
  updatePlanProcessStatus, //审核
  getPlanReadyProcessList, //我已审核
  selectPlanProcessLogList, //审核日志
  getPlanMyProcessList, //我发起的审核
  revokePlan, //撤回
} from "@/api/sale/plan";
import { productTreeSelect } from "@/api/commodity/products";
import { getPlatFormTree } from "@/api/walmart/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { formatPath } from "@/api/utils/pathUtils";
import store from "@/store";
export default {
  name: "Plan",
  dicts: ["tb_plan", "sys_job_status", "sys_sales_shipment_status"],
  components: { Treeselect },
  data() {
    return {
      // currentDefaultDate: new Date().toISOString().split("T")[0].toISOString(),
      // 遮罩层
      loading: true,
      loadingProduct: true,
      // 选中数组
      ids: [],
      productIds: [],
      // 子表选中数据
      checkedShipmentsProduct: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalProduct: 0,
      // 销售中心表格数据
      planList: [],
      // 分类管理表格数据
      productList: [],
      // 发货产品表格数据
      shipmentsProductList: [],
      // 弹出层标题
      title: "",
      titleName: "",
      // 是否显示弹出层
      open: false,
      productOpen: false,
      //产品名称
      productsName: null,
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 产品管理表格数据
      productsList: [],
      // 分类管理树选项
      productsOptions: [],
      // 计划状态
      nameStatus: null,
      nickName: null,
      nickNameReviewed: null,
      shipmentStatusOptions: [],
      defaultShipmentStatus: {
        children: "children",
        label: "label",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planName: null,
        planStatus: null,
        procuredPlanNumber: null,
        procuredOrdersNumber: null,
        planNumber: null,
        searchSku: null
      },
      // 产品查询参数
      queryParamProduct: {
        pageNum: 1,
        pageSize: 10,
        catesId: null,
        name: null,
        status: null,
        authId: null,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        freightMethod: [
          { required: true, message: "请输入货运方式", trigger: "blur" },
        ],
        planName: [
          {
            required: true,
            message: "请输入计划名称",
            trigger: "blur",
            validator: (rule, value, callback) => {
              // 判断 value 是否存在并且是字符串类型
              if (value && typeof value === "string" && value.trim() === "") {
                callback(new Error("请输入计划名称")); // 去掉空格后为空，则提示
              } else if (!value || typeof value !== "string") {
                callback(new Error("计划名称不能为空")); // 如果 value 为 null 或 undefined
              } else {
                callback(); // 验证通过
              }
            },
          },
        ],
      },
      // 货运方式
      freightMethodOptions: [],
      //审核提示
      audit: "",
      //审核弹出框
      openAudit: false,
      //审核内容
      formAudit: {},
      //存储审核中的数据
      auditData: [],
      auditLength: null,
      drawer: false,
      drawerValue: {},
      productLength: null,
      postUserDept: [],
      postUserDeptLength: null,
      squareUrl:
        "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
      currentDateTime: "",
      approvalProcess: {},
      ApprovalProcessStatus: [],
      ApprovalProcessLength: null,
      //当前用户id
      userId: store.getters.userId,
      //当前用户所在的部门id
      deptId: store.getters.deptId,
      //获得已审批的数据
      planReviewed: [],
      //获得已审批的数据条数
      planReviewedLenght: null,
      //获得我发起的审批数据
      planInitiated: [],
      //获得我发起的审批数据条数
      planInitiatedLenght: null,
      //店铺下拉列表
      platFormOptions: [],
      //判断是修改还是详情
      decide: true,
      selectionList: [], //添加销售计划中添加产品窗口选中产品的数据集
      activeTab: "toAudit",
      pageParams: {
        toAudit: { pageNum: 1, pageSize: 10 },
        audited: { pageNum: 1, pageSize: 10 },
        myAudit: { pageNum: 1, pageSize: 10 },
      },
      tabData: {
        toAudit: [], //待我审核
        audited: [], //我已审核
        myAudit: [], //我的发起
      },

      tabTotals: {
        toAudit: 0,
        audited: 0,
        myAudit: 0,
      },
      planProcessData: [], //审核流程
      isSubmitting: false,
      planProcessRemark: "", //审核拒绝备注
      openLog: false, //审核日志
      PlanProcessLogList: [],
      // 查询参数
      logParam: {
        pageNum: 1,
        pageSize: 10,
      },
      logTotals: 0,
      currentSkuIndices: null,
      //撤回模块
      openRevoke: false,
      dialogVisible: false,
      revoke: { remark: "" },
      checkProcuredPlanNumber: "",
      checkPlanId: "",
      checkUserName: "",
      // ========= 提前结束按钮点击弹窗相关参数
      // 弹窗控制
      showEndPlanDialog: false,
      // 结束后的发货数量
      endShippingQuantity: null,
      // 需要传递的参数
      currentPlanId: null,
      currentDetailId: null,
    };
  },
  computed: {
    imageCount() {
      return this.ApprovalProcessStatus.filter((item) => item.status == 1)
        .length;
    },
  },
  created() {
    this.getList();
    this.getStatus();
    this.getProductTree();

    this.getTree();
    this.getPlanStatus();
    setInterval(() => {
      const date = new Date();
      this.currentDateTime = date.toLocaleString();
    }, 1000);
    this.getPlatForm();
  },
  watch: {
    // 根据名称筛选部门树
    nameStatus(val) {
      this.$refs.tree.filter(val);
    },
    // 根据产品名称筛选部门树
    productsName(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {
    // 分组：统计每个 sku 的首行索引和合并数量
    // 修正skuGroups计算属性，确保它能正确处理所有情况
    skuGroups() {
      const groups = {};
      if (
        !this.shipmentsProductList ||
        this.shipmentsProductList.length === 0
      ) {
        return groups;
      }

      this.shipmentsProductList.forEach((row, index) => {
        const sku = row.sku;
        if (sku) {
          // 确保sku不为空
          if (!groups[sku]) {
            groups[sku] = {
              start: index,
              count: 1,
            };
          } else {
            groups[sku].count++;
          }
        }
      });

      return groups;
    },

    // 统计每个 sku 的计划数量总和
    skuPlanTotals() {
      const totals = {};
      this.shipmentsProductList.forEach((row) => {
        const sku = row.sku;
        totals[sku] = (totals[sku] || 0) + (Number(row.planSize) || 0);
      });
      return totals;
    },
  },
  methods: {
    // el-table 的 span-method，用于合并单元格
    tableSpanMethod({ row, column, rowIndex }) {
      // 对以下列进行合并：图片、名称、sku、以及总计数量列
      const mergeColumns = ["imgName", "name", "sku", "totalPlan"];

      if (mergeColumns.includes(column.property)) {
        // 确保skuGroups已经计算完成
        if (this.skuGroups) {
          const sku = row.sku;
          if (sku && this.skuGroups[sku]) {
            const group = this.skuGroups[sku];

            // 如果当前行为该sku分组的第一行，则返回该组的行数，否则合并（即返回0）
            if (rowIndex === group.start) {
              return {
                rowspan: group.count,
                colspan: 1,
              };
            } else {
              return {
                rowspan: 0,
                colspan: 0,
              };
            }
          }
        }
      }

      // 默认不合并
      return {
        rowspan: 1,
        colspan: 1,
      };
    },

    handleChange(selected) {
      if (Array.isArray(selected) && selected.length > 0) {
        // 取数组的最后一个元素作为最终值
        this.form.goShop = selected[selected.length - 1];
      } else {
        this.form.goShop = selected;
      }
    },

    /** 查询店铺名称列表 */
    getPlatForm() {
      getPlatFormTree().then((response) => {
        this.platFormOptions = response.data;
      });
    },
    /** 查询部门下拉树结构 */
    getProductTree() {
      productTreeSelect().then((response) => {
        this.productsOptions = response.data;
      });
    },
    getStatus() {
      getShipmentStatus().then((response) => {
        this.shipmentStatusOptions = response.data;
      });
    },
    /** 查询销售中心列表 */
    getList() {
      this.loading = true;

      listPlan(this.queryParams).then((response) => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 查询审核中的条数
    getPlanStatus() {
      this.queryParams.planStatus = 4;
      this.queryParams.userId = this.userId;
      if (this.userId != 1) {
        this.queryParams.deptId = this.deptId;
      }

      this.queryParams.planStatus = null;
      this.queryParams.userId = null;
      this.queryParams.deptId = null;
    },
    /** 查询产品列表 */
    getListProduct() {
      this.loadingProduct = true;
      this.queryParamProduct.authId = this.form.goShop;
      getSelectItemPlan(this.queryParamProduct).then((response) => {
        this.productsList = response.rows;
        this.totalProduct = response.total;
        this.loadingProduct = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        planNumber: null,
        planName: null,
        goShop: null,
        freightMethod: null,
        nickName: null,
        planStatus: null,
        platForm: null,
        shipTime: new Date(),
        preparationTime: null,
        approver: null,
        auditTime: null,
        productsSplicing: null,
        remark: null,
        updateTime: null,
        deleteStatus: null,
      };
      this.shipmentsProductList = [];
      this.resetForm("form");
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    //产品节点单机事件
    handleNodeClickProduct(data) {
      this.queryParamProduct.catesId = data.id;
      this.handleQueryProduct();
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.planStatus = data.status;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 产品搜索按钮操作 */
    handleQueryProduct() {
      this.queryParamProduct.pageNum = 1;
      this.getListProduct();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetQueryProduct() {
      this.resetForm("queryFormProduct");
      this.handleQueryProduct();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectionList = selection;
      this.ids = selection.map((item) => item.id);
      this.productIds = selection.map((item) => item.productId);
      this.gtins = selection.map((item) => item.gtin);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      // 判断 selection 是否至少有一项
      if (selection.length > 0) {
        this.checkPlanId = selection[0].id;
        this.checkProcuredPlanNumber = selection[0].procuredPlanNumber;
        this.checkUserName = selection[0].nickName;
      } else {
        // 当 selection 为空时可以设置为默认值或者清空
        this.checkPlanId = null;
        this.checkProcuredPlanNumber = null;
        this.checkUserName = null;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加销售中心";
      this.decide = true;
    },
    convertStringToArray(str) {
      return str.split(",");
    },
    /**修改按钮操作*/
    handleUpdate(row) {
      this.reset();
      // 处理从表格行点击的情况
      if (row && row.id) {
        const id = row.id;
        // 只有当计划状态为6时才进行修改
        if (row.planStatus == 6) {
          getPlan(id).then((response) => {
            this.form = response.data;
            // this.form.platForm = this.convertStringToArray(response.data.ancestors);
            this.form.platForm = this.form.goShop.toString();
            // 确保产品列表按SKU排序，便于合并单元格
            let products = response.data.shipmentsProductList || [];
            if (products.length > 0) {
              products.sort((a, b) => {
                if (a.sku < b.sku) return -1;
                if (a.sku > b.sku) return 1;
                return 0;
              });
            }
            this.shipmentsProductList = products.map((item) => {
              return {
                ...item,
                sellerSku: item.itemSku,
                productRemarks: item.remark,
              };
            });
            this.open = true;
            this.title = "修改销售中心";
            this.decide = true;
          });
        } else {
          this.$message.error("只能修改未审核中的销售计划！");
        }
      }
      // 处理从工具栏按钮点击(使用选中的行)的情况
      else if (this.ids.length > 0) {
        // 检查所有选中的行是否都是状态6
        const hasNonEditableItems = this.selectionList.some(
          (item) => item.planStatus != 6
        );

        if (hasNonEditableItems) {
          this.$message.error(
            "只能修改未审核中的销售计划！请确保所有选中项都是未审核状态。"
          );
          return;
        }

        // 如果只选中了一项且状态正确，则进行修改
        if (this.selectionList.length === 1) {
          const id = this.ids[0];
          getPlan(id).then((response) => {
            this.form = response.data;
            // this.form.platForm = this.convertStringToArray(response.data.ancestors);
            this.form.platForm = this.form.goShop.toString();
            this.shipmentsProductList = response.data.shipmentsProductList;
            // 确保产品列表按SKU排序，便于合并单元格
            let products = response.data.shipmentsProductList || [];
            if (products.length > 0) {
              products.sort((a, b) => {
                if (a.sku < b.sku) return -1;
                if (a.sku > b.sku) return 1;
                return 0;
              });
            }

            this.shipmentsProductList = products.map((item) => {
              return {
                ...item,
                sellerSku: item.itemSku,
                productRemarks: item.remark,
              };
            });
            this.open = true;
            this.title = "修改销售中心";
            this.decide = true;
          });
        } else {
          this.$message.error("请只选择一条记录进行修改");
        }
      } else {
        this.$message.error("请选择要修改的数据");
      }
    },

    /** 详情按钮 */
    handlePlanQuery(row) {
      this.reset();
      const id = row.id || this.ids;
      getPlan(id).then((response) => {
        this.form = response.data;
        // this.form.platForm = this.convertStringToArray(response.data.ancestors);
        this.form.platForm = this.form.goShop.toString();
        // 在 platFormOptions 中查找与选定值匹配的路径
        this.shipmentsProductList = response.data.shipmentsProductList;
        this.open = true;
        this.title = "详情销售中心";
        this.decide = false;
      });
    },

    /** 提交按钮 */
    submitForm() {
      // 保存当前路径用于重定向
      let originalPath = this.$route.path;
      let componentPath = formatPath(originalPath);

      this.$refs["form"].validate(async (valid) => {
        if (!valid) return;

        // 特殊情况检查 - 新增时需要有产品数据
        if (!this.form.id && this.shipmentsProductList.length === 0) {
          this.$message.error("请添加产品数据！");
          return;
        }

        // 校验产品计划数量
        const isValidPlanSize = this.shipmentsProductList.every((item) => {
          // 处理不同数据类型的情况
          if (item.planSize === null || item.planSize === undefined) {
            return false; // 空值无效
          }

          // 如果是字符串，确保非空且可转为数字
          if (typeof item.planSize === "string") {
            return item.planSize.trim() !== "" && !isNaN(Number(item.planSize));
          }

          // 如果是数字，直接判断是否有效
          return !isNaN(item.planSize);
        });

        if (!isValidPlanSize) {
          this.$message.error("计划数量必须填写且为有效数字！");
          return;
        }

        // 将产品列表添加到表单
        this.form.shipmentsProductList = this.shipmentsProductList;

        try {
          // 根据是否有ID判断是修改还是新增
          if (this.form.id) {
            await updatePlan(this.form);
            this.$modal.msgSuccess("修改成功");
          } else {
            // 新增操作
            await addPlan(this.form, componentPath);
            this.$modal.msgSuccess("新增成功");
          }

          // 成功后关闭表单并刷新列表
          this.open = false;
          this.getList();
        } catch (error) {
          console.error("提交表单失败:", error);
          this.$message.error("操作失败，请重试");
        }
      });
    },

    /**删除按钮操作*/
    handleDelete(row) {
      // 定义要删除的ID
      const ids = row?.id || this.ids;

      // 如果没有选择任何数据
      if (!ids || (Array.isArray(ids) && ids.length === 0)) {
        this.$modal.msgError("请选择要删除的数据");
        return;
      }

      // 检查是单行删除还是批量删除
      if (row && row.id) {
        // 单行删除 - 检查状态
        if (row.planStatus != 6) {
          this.$modal.msgError("只能删除未审核中的销售计划！");
          return;
        }
      } else {
        // 批量删除 - 检查所有选中项状态
        const hasNonDeletableItems = this.selectionList.some(
          (item) => item.planStatus != 6
        );
        if (hasNonDeletableItems) {
          this.$modal.msgError(
            "只能删除未审核中的销售计划！请确保所有选中项都是未审核状态。"
          );
          return;
        }
      }

      // 所有检查通过，执行删除操作
      const deleteMsg = Array.isArray(ids)
        ? `是否确认删除选中的${ids.length}条销售中心数据项？`
        : `是否确认删除销售中心编号为"${ids}"的数据项？`;

      this.$modal
        .confirm(deleteMsg)
        .then(() => {
          // 这里使用箭头函数保持this指向
          return delPlan(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.getPlanStatus();
        })
        .catch(() => {
          // 可以在这里添加错误处理
        });
    },

    async handleEndPlan(planId, detailId, planNumber) {
      try {
        // 先查询是否有相关采购订单
        const response = await SearchRelatedPurchaseOrders(
          planNumber,
          detailId
        );

        if (response.data.length > 0) {
          const purchaseOrders = response.data;
          const orderNumbers = purchaseOrders
            .map((order) => order)
            .join("、");

          // 发现采购订单，询问用户是否跳转查看
          this.$confirm(
            `检测到相关的采购订单：${orderNumbers}，是否跳转到采购订单页面进行撤回操作？`,
            "发现相关采购订单",
            {
              confirmButtonText: "跳转查看",
              cancelButtonText: "继续结束",
              type: "warning",
              customClass: "purchase-order-confirm",
            }
          )
            .then(() => {
              // 用户选择跳转到采购订单页面
              this.jumpToPurchaseOrderPage(purchaseOrders);
            })
            .catch(() => {
              // 用户选择继续提前结束流程
              this.proceedWithEndPlan(planId, detailId);
            });
        } else {
          // 没有相关采购订单，直接进入提前结束流程
          this.proceedWithEndPlan(planId, detailId);
        }
      } catch (error) {
        console.error("查询相关采购订单失败:", error);
      }
    },
    proceedWithEndPlan(planId, detailId) {
      this.currentPlanId = planId;
      this.currentDetailId = detailId;
      this.showEndPlanDialog = true; // 打开原来的数量输入弹窗
    },
    // 新增：跳转到采购订单页面
    jumpToPurchaseOrderPage(orderNumbers) {
      this.$router.push({
        name: "ProcuredOrders", // 使用路由名称
        query: {
          highlightOrders: orderNumbers.join(","),
          fromSales: "true",
        },
      });
    },

    // 关闭弹窗
    closeEndPlanDialog() {
      this.showEndPlanDialog = false;
      this.endShippingQuantity = null; // 清空发货数量
    },

    // 提交提前结束的操作
    submitEndPlan() {
      // 你可以在这里进行发货数量的验证，确保输入的是有效的数字
      if (this.endShippingQuantity < 0) {
        this.$message.error("请输入有效的发货数量！");
        return;
      }

      // 发起请求
      endPlan({
        planId: this.currentPlanId,
        detailId: this.currentDetailId,
        count: this.endShippingQuantity,
      })
        .then((response) => {
          this.$message.success("提前结束销售计划成功！");
          this.closeEndPlanDialog(); // 关闭弹窗
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("操作失败，请稍后再试");
        });
    },

    /** 发货产品序号 */
    rowShipmentsProductIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 分类管理添加按钮操作 */
    handleAddShipmentsProduct() {
      if (this.form.goShop != null) {
        this.titleName = "添加产品";
        this.productOpen = true;
        this.getListProduct();
      } else {
        this.$message.warning("请选择发往店铺");
      }
    },
    /** 分类管理删除按钮操作 */
    handleDeleteShipmentsProduct() {
      if (this.checkedShipmentsProduct.length == 0) {
        this.$modal.msgError("请先选择要删除的发货产品数据");
      } else {
        const shipmentsProductList = this.shipmentsProductList;
        const checkedShipmentsProduct = this.checkedShipmentsProduct;
        this.shipmentsProductList = shipmentsProductList.filter(function (
          item
        ) {
          return checkedShipmentsProduct.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleShipmentsProductSelectionChange(selection) {
      this.checkedShipmentsProduct = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "sale/plan/export",
        {
          ...this.queryParams,
        },
        `plan_${new Date().getTime()}.xlsx`
      );
    },
    /** 添加产品 */
    submitFormProduct() {
      const productIds = this.productIds;
      if (!productIds || productIds.length <= 0) {
        this.$message("请至少选择一条产品数据！");
        return;
      }
      // 检查是否有任何 `walmartProductName` 为空的项
      const hasEmptyWalmartProductName = this.selectionList.some(
        (item) => !item.walmartProductName
      );

      if (hasEmptyWalmartProductName) {
        // 弹出提示信息
        this.$message.error(
          "添加的产品包含尚未配对 Walmart 产品的链接，请检查并补充 Walmart 链接产品关联信息！"
        );
        return;
      }
      const obj = {
        productIds: productIds,
        goShop: this.form.goShop,
        gtins: this.gtins,
      };

      getSelectPairId(obj).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          let newItem = {
            imgName: response.data[i].imgName,
            name: response.data[i].name,
            productFnsku: "",
            price: response.data[i].price,
            sentSize: "0",
            operSize: "0",
            planSize: "",
            amount: "",
            sellerSku: response.data[i].sellerSku,
            gtin: response.data[i].gtin,
            sku: response.data[i].sku,
            productRemarks: response.data[i].productRemarks,
            productId: response.data[i].productId,
          };

          // 检查 shipmentsProductList 中是否存在 sku 和 gtin 都相同的数据
          let exists = this.shipmentsProductList.some(
            (item) => item.sku === newItem.sku && item.gtin === newItem.gtin
          );

          if (!exists) {
            this.shipmentsProductList.push(newItem);
          }
        }
      });

      this.productOpen = false;
      this.$refs.myTable.clearSelection();
    },
    /** 取消产品 */
    cancelProduct() {
      this.productOpen = false;
      this.$refs.myTable.clearSelection();
    },
    autoFillModel(row) {
      row.operSize = row.planSize * 1;
      row.amount = (row.planSize * row.price).toFixed(2);
      if (row.amount == 0) {
        row.amount = "";
      }
    },
    /** 查询货运方式 */
    getTree() {
      getFreightMethodTree().then((response) => {
        this.freightMethodOptions = response.data;
      });
    },
    /** 弹出审核 */

    handleAudit() {
      const nickName = this.$store.state.user.nickName;
      if (nickName != this.checkUserName) {
        this.$message.error(
          "当前用户【" +
            nickName +
            "】，与销售计划制单人【" +
            this.checkUserName +
            "】不匹配，请重新选择"
        );
        return;
      }
      if (this.checkProcuredPlanNumber) {
        this.$message.error(
          "销售计划已关联采购计划【" +
            this.checkProcuredPlanNumber +
            "】，不允许撤回"
        );
        return;
      }
      this.dialogVisible = true;
      this.openRevoke = true;
    },
    closeRevoke() {
      this.dialogVisible = false;
      this.openRevoke = false;
    },
    //弹出审核中
    underReview() {
      this.openAudit = true;
      this.audit = "审批统计";
      this.activeTab = "toAudit";
      this.loadData();
    },
    // 点击确定，提交撤回操作
    confirmWithdraw() {
      if (!this.revoke.remark.trim()) {
        this.$message.warning("请输入撤回备注");
        return;
      }
      const planId = this.checkPlanId;
      this.revoke.id = planId;
      let originalPath = this.$route.path; // 当前路径
      let componentPath = formatPath(originalPath);
      revokePlan(this.revoke, componentPath).then((r) => {
        this.$message.success("撤回成功");
        this.closeRevoke();
        this.getList();
      });
    },

    cancelTreat() {
      this.openAudit = false;
    },
    borderTrigger(data) {
      this.drawer = true;
      this.drawerValue = data;
      getPlanProcessList(data.id).then((r) => {
        this.PaymentRequestProcessLength = r.data.length;
        this.planProcessData = r.data;
      });
    },

    /** 审批同意按钮 */
    async approvePlan(planId, planProcessStatus) {
      // 避免重复提交
      if (this.isSubmitting) return;

      this.approvalProcess.planId = planId;
      this.approvalProcess.planProcessStatus = planProcessStatus;
      this.approvalProcess.planProcessRemark = this.planProcessRemark;

      try {
        await updatePlanProcessStatus(this.approvalProcess);
        let title = "同意审批";
        if (planProcessStatus != 1) {
          title = "拒绝审批";
        }
        this.$modal.msgSuccess(title);
        this.drawer = false;
        this.loadData();
        this.getList();
      } catch (error) {
        this.$modal.msgError("提交审批中中，请勿重复提交");
      } finally {
        this.isSubmitting = false; // 请求完成后解锁
      }
    },
    /** 审批拒绝按钮 */
    rejectPlan(planId, planProcessStatus) {
      if (!this.planProcessRemark) {
        this.$message.error("请填写备注");
        return;
      }
      this.approvePlan(planId, planProcessStatus);
    },
    loadData() {
      const tab = this.activeTab;
      const { pageNum, pageSize } = this.pageParams[tab];
      //待我审核
      if (tab === "toAudit") {
        const params = {
          planStatus: 6,
          reviewerUserId: this.userId,
          userName: this.nickName,
          pageNum,
          pageSize,
        };
        getPlanWaitProcessList(params).then((res) => {
          this.tabData.toAudit = res.rows;
          this.tabTotals.toAudit = res.total;
        });
      }
      /** 查询自己已审批的数据 */
      if (tab === "audited") {
        const params = {
          userId: this.userId,
          userName: this.nickNameReviewed,
          pageNum,
          pageSize,
        };
        getPlanReadyProcessList(params).then((res) => {
          this.tabData.audited = res.rows;
          this.tabTotals.audited = res.total;
        });
      }
      /** 查询自己发送的审批数据 */
      if (tab === "myAudit") {
        const params = {
          userId: this.userId,
          pageNum,
          pageSize,
        };
        getPlanMyProcessList(params).then((res) => {
          this.tabData.myAudit = res.rows;
          this.tabTotals.myAudit = res.total;
        });
      }
    },
    handleTabClick(tab) {
      this.pageParams[tab.name].pageNum = 1;
      this.activeTab = tab.name;
      this.loadData();
    },

    handlePagination({ page, limit }) {
      this.pageParams[this.activeTab].pageNum = page;
      this.pageParams[this.activeTab].pageSize = limit;
      this.loadData();
    },

    /** 查询自己已审批的数据 */
    getSelectPlanReviewed() {
      this.readyProcess.userId = this.userId;
      this.readyProcess.nickName = this.nickNameReviewed;
      getPlanReadyProcessList(this.readyProcess).then((response) => {
        this.planReviewedLenght = response.total;
        this.planReviewed = response.rows;
      });
    },
    /** 查询自己发送的审批数据 */
    getPlanInitiated() {
      this.myProcess.userId = this.userId;
      getPlanMyProcessList(this.myProcess).then((response) => {
        this.planInitiatedLenght = response.total;
        this.planInitiated = response.rows;
      });
    },
    //查审核日志
    planProcessLog(row) {
      this.openLog = true;
      this.logParam.planId = row.id;
      this.getPlanProcessLogList();
    },
    //查询所有的申请记录
    getPlanProcessLogList() {
      this.loading = true;
      selectPlanProcessLogList(this.logParam).then((response) => {
        this.PlanProcessLogList = response.rows;
        this.logTotals = response.rows.length;
        this.loading = false;
      });
    },
    cancelPlanProcessLog() {
      this.openLog = false;
    },
    /** 跳转到打印页面 */
    goToPrintPage() {
      const printData = this.selectionList[0];

      // 使用路由跳转到打印页面，并将打印数据传递给路由
      this.$router.push({
        name: "PrintPage",
        params: { printData: printData },
      });
    },

    /***处理表格展开事件*/
    handleExpandChange(row, expandedRows) {
      if (
        row &&
        row.shipmentsProductList &&
        row.shipmentsProductList.length > 0
      ) {
        // 1. 确保首先对数据按SKU排序
        row.shipmentsProductList.sort((a, b) => {
          const skuA = a.sku || "";
          const skuB = b.sku || "";
          if (skuA < skuB) return -1;
          if (skuA > skuB) return 1;
          return 0;
        });

        // 2. 初始化处理对象
        const skuMap = {};
        const skuFirstRow = {};
        const skuTotals = {};

        // 3. 第一次遍历：标记每个SKU的首行和计算合计
        row.shipmentsProductList.forEach((item, index) => {
          const sku = item.sku || "";
          if (!skuMap[sku]) {
            skuMap[sku] = [];
            skuFirstRow[sku] = index;
            skuTotals[sku] = 0;
          }
          skuMap[sku].push(index);

          // 累加计划数量
          const planSize = parseFloat(item.planSize) || 0;
          skuTotals[sku] += planSize;
        });

        // 4. 第二次遍历：为每行添加合并标记和SKU合计
        row.shipmentsProductList.forEach((item, index) => {
          const sku = item.sku || "";
          item._skuFirstRow = skuFirstRow[sku];
          item._skuRowspan = skuMap[sku].length;
          item._rowIndex = index;
          item._skuTotal = skuTotals[sku];
        });
      }

      // 5. 确保表格重新渲染
      this.$nextTick(() => {
        // 找到展开的表格
        const expandedTables = document.querySelectorAll(
          ".el-table__expanded-cell .el-table"
        );
        expandedTables.forEach((table) => {
          const instance = table.__vue__;
          if (instance && instance.doLayout) {
            instance.doLayout();
          }
        });
      });
    },

    /**
     * 嵌套表格单元格合并方法 - 直接使用预处理的合并信息
     */
    /***嵌套表格单元格合并方法-直接使用预处理的合并信息*/
    /***嵌套表格单元格合并方法-直接使用预处理的合并信息*/
    nestedTableSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 基本合并逻辑保持不变
      const mergeColumns = ["imgName", "name", "sku"];

      // 图片、名称、SKU的合并
      if (mergeColumns.includes(column.property)) {
        // 确保存在sku和合并信息
        if (
          row.sku &&
          row._rowIndex !== undefined &&
          row._skuFirstRow !== undefined
        ) {
          if (row._rowIndex === row._skuFirstRow) {
            return { rowspan: row._skuRowspan, colspan: 1 };
          } else {
            return { rowspan: 0, colspan: 0 };
          }
        }
      }

      // 处理合计数量列 - 这里是修改的关键部分
      if (column.label === "合计数量") {
        // 只在每个SKU组的第一行显示合计
        if (row._rowIndex === row._skuFirstRow) {
          return { rowspan: row._skuRowspan, colspan: 1 };
        } else {
          return { rowspan: 0, colspan: 0 };
        }
      }

      // 默认不合并
      return { rowspan: 1, colspan: 1 };
    },

    /**
     * 计算嵌套表格中每个 SKU 的计划数量合计
     * @param {string} sku - SKU 值
     * @param {Array} tableData - 表格数据
     * @returns {number} 合计数量
     */
    getNestedSkuTotal(sku, tableData) {
      if (!tableData || !sku) return 0;

      let total = 0;
      tableData.forEach((item) => {
        if (item.sku === sku && item.planSize) {
          // 转换为数字并累加
          const planSize = parseFloat(item.planSize) || 0;
          total += planSize;
        }
      });

      return total;
    },
  },
};
</script>
<style>
.ellipsis-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
  /* 可以根据实际需求调整 */
  display: inline-block;
}

.auditStyle {
  width: 1166px;
}

.el-dialog__body {
  padding: 0px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}

.show-frame {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
  height: 70px;
  margin-bottom: 10px;
}

.show-frame-container {
  overflow: auto;
  height: 560px;
  /* 设置容器的高度 */
}

.el-image {
  border-radius: 5px;
  background-color: #ebeef5;
  box-shadow: 0 0 5px 1px #ccc;
  transform: translateY(9px);
  /* left: 19px; */
}

.plan-size {
  display: block;
  transform: translateY(-60px);
  margin-left: 94px;
}

.h1,
.h2,
.h3,
.h4,
.h5,
.h6,
h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: inherit;
  font-weight: 500;
  line-height: 1.1;
  color: black;
  font-weight: bold;
}

.singleHanded-css {
  display: block;
  margin-left: 94px;
  margin-top: -66px;
}

.planNumber-css {
  display: block;
  margin-top: -50px;
  margin-left: 375px;
}

.mannerName-css {
  display: block;
  margin-top: 11px;
  margin-left: 375px;
}

.planProcessTime-css {
  display: block;
  margin-top: -50px;
  margin-left: 655px;
}

.planProcessStatus-css {
  display: flex;
  /* 使用 flexbox 布局 */
  align-items: center;
  /* 垂直居中 */
  gap: 15px;
  /* 控制子元素之间的间距 */
  margin-top: 5px;
  margin-left: 655px;
  /* 可调整 */
}

.shipTime-css {
  display: block;
  margin-top: -50px;
  margin-left: 934px;
}

.shipTimeReady-css {
  display: block;
  margin-top: -58px;
  margin-left: 934px;
}

.shipTimeMy-css {
  display: block;
  margin-top: -50px;
  margin-left: 984px;
}

.planStatus-css {
  display: flex;
  margin-top: 10px;
  margin-left: 934px;
}

.planStatusMy-css {
  display: flex;
  margin-top: 10px;
  margin-left: 984px;
}

.center-title .el-drawer__title {
  text-align: center;
}

.drawerValueUserImg {
  display: block;
}

.drawerValueSingleHanded {
  display: block;
  margin-top: -65px;
  margin-left: 96px;
}

.drawerValuePlanStatus {
  display: block;
  margin-top: -13px;
  margin-left: 98px;
}

.el-descriptions--mini:not(.is-bordered) .el-descriptions-item__cell {
  padding-bottom: 9px;
  font-size: 13px;
}

.margin-top {
  display: block;
  margin-top: 16px;
  margin-left: 20px;
}

.margin-top1 {
  display: block;
  margin-top: -47px;
  margin-left: 89px;
}

hr {
  border-color: #0000;
  height: 7px;
  background-color: #f3f3f3;
}

.el-descriptions-item__label.has-colon::after {
  content: ":";
  position: relative;
  top: -0.5px;
  display: none;
}

.sponsor {
  font-size: 14px;
  display: block;
  margin-top: -41px;
  margin-left: 96px;
}

.sponsor-name {
  font-size: 12px;
  display: block;
  margin-top: 4px;
  margin-left: 96px;
  color: #6f7174;
}

.sponsor-time {
  font-size: 12px;
  display: block;
  margin-top: -34px;
  margin-left: 439px;
  color: #6f7174;
}

.postUserDept-css {
  display: block;
  margin-top: 30px;
  height: 36px;
}

.postUserDept-postName {
  font-size: 12px;
  display: block;
  margin-top: 3px;
  margin-left: 439px;
  color: #6f7174;
}

.block {
  display: block;
  margin-left: 19px;
  margin-top: 55px;
}

.ccPerson {
  font-size: 14px;
  display: block;
  margin-top: -51px;
  margin-left: 96px;
}

.approval {
  position: fixed;
  right: 28px;
  bottom: 20px;
}

.approvalProcess-container {
  display: flex;
  flex-wrap: nowrap;
  margin-left: 78px;
  margin-top: 18px;
}

.approvalProcess-image {
  float: left;
  margin-right: 3px;
  /* 调整图片之间的间距 */
}

.approvalProcess-size {
  font-size: 12px;
  display: block;
  color: #6f7174;
  margin-left: 15px;
  margin-top: 10px;
}

._scroll-container {
  margin-top: 45px;
  height: 250px;
  max-height: 300px;
  /* 设置最大高度 */
  overflow-y: auto;
  /* 垂直滚动 */
  border: 2px solid #ccc;
  /* 边框可选 */
}

.processRemark-input {
  width: 70%;
  /* 占满可用宽度 */
  margin-bottom: 20px;
  /* 与按钮组的间距 */
}

.button-group {
  display: flex;
  float: right;
  transform: translateX(-30%);
  /* 修正因right的偏移 */
  gap: 50px;
  /* 按钮之间的间距 */
}

.approval {
  position: sticky;
  bottom: 20px;
  flex-direction: column;
  align-items: flex-start;
  /* 靠左对齐 */
  margin-top: 10px;
}

.plan-number-display {
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.plan-number-display:hover {
  background-color: #f5f7fa;
}

.more-indicator {
  color: #909399;
  font-size: 12px;
  margin-left: 4px;
}
</style>
